# -*- coding: utf-8 -*-
import json
import logging

from common.update import handler
from common.stats import MG_BIGBANG_COLL as mg

from common.utils.decorator import response_wrapper
from common.utils.exceptions import ResourceNotModified, ResourceNotFound
from common.utils.api import get_client_ua

from django.http import HttpResponseRedirect
from django.views.decorators.http import require_GET


_LOGGER = logging.getLogger('bigbang')
_TRACKER = logging.getLogger('tracker')


@require_GET
@response_wrapper
def get_update(request):
    """
    update service
    """
    pkg = request.GET.get('pn')
    chn = request.GET.get('chn')
    cvc = int(request.GET.get('vc', 0))
    data = handler.get_latest(pkg, chn, cvc, is_delta=False)
    if not data:
        raise ResourceNotFound()
    if cvc >= data['cvc']:
        raise ResourceNotModified()
    return {
        'cvc': data['cvc'],
        'cvn': data['cvn'],
        'url': data['url'],
        'content': data['content'],
        'force': data['force']
    }


@require_GET
@response_wrapper
def get_patch(request):
    """
    patch service
    """
    pkg = request.GET.get('pn')
    chn = request.GET.get('chn')
    cvc = int(request.GET.get('vc', 0))
    data = handler.get_latest(pkg, chn, cvc, is_delta=True)
    if not data:
        raise ResourceNotFound()
    if cvc >= data['cvc']:
        raise ResourceNotModified()
    return {
        'cvc': data['cvc'],  # version code for path
        'url': data['url']
    }


@require_GET
@response_wrapper
def download_url(request):
    """
    download service
    """
    source = request.GET.get('source')
    ua = get_client_ua(request)
    _LOGGER.info('download_url, source:%s, ua:%s', source, ua)
    return HttpResponseRedirect('')


TARGET_CVCS = [17, 18]
LATEST_CVC = 19
LATEST_URL = 'http://op7v49fgn.bkt.clouddn.com/BigBang_fc_release.apk?v=2.0.2'
LATEST_UPDATE_INFO = u'1. 新增部分热门彩种\n2. 提升了部分彩种的奖金\n3. 优化了首页彩种展示\n4. 优化了购彩助手的体验\n5. 优化了智能追号体验\n6. 修复了部分bug'


@require_GET
@response_wrapper
def get_update_info(request):
    """
    get update info by uid
    """
    user_id = request.user_id
    user_stats = mg.user_stats.find_one({'_id': user_id}) or {}
    user_cvc = user_stats.get('cvc', 0)
    if user_cvc in TARGET_CVCS:
        return {
            'cvc': LATEST_CVC,
            'url': LATEST_URL,
            'info': LATEST_UPDATE_INFO
        }
    return {
        'cvc': LATEST_CVC,
        'info': LATEST_UPDATE_INFO
    }
